from plugins.template import ParserTemplate
import re

def get_parsers():
	return {"Kal": Parser}


class Parser(ParserTemplate):
	"""
	Grammar:
	Page = Number NL.
	Text = Translation NL.

	panels are split by newlines

	>>> from io import StringIO
	>>> text = '''031
	...
	...     Text1
	...     [sfx]
	...
	...     Text2
	...
	...     032
	...
	...     Text3'''
	>>> parser = Parser(StringIO(text))
	>>> parser.next_token()
	Token(page='031', panel='1', text='Text1', line=2)
	>>> parser.next_token()
	Token(page='031', panel='1', text='sfx', line=3)
	>>> parser.next_token()
	Token(page='031', panel='2', text='Text2', line=5)
	>>> parser.next_token()
	Token(page='032', panel='1', text='Text3', line=9)
	>>> parser.next_token()
	"""

	_PageRe = re.compile('''(\d+)	# simple number as group
		$ # end''', re.VERBOSE | re.IGNORECASE)

	def __init__(self, file):
		self._empty_line_above = False
		super().__init__(file)


	def _next_line(self):
		""" Has to be overwritten because we need the empty_line_above
			 attribute, otherwise identical to original"""
		try:
			line = self._readline()
			self._empty_line_above = False
			while not line:
				self._empty_line_above = True
				line = self._readline()
			self._line = line
		except self.EofError:
			# we don't forward the exception here, instead we only
			# throw the exception when someone tries to read the line
			self._line = None

	def _parse_next(self, last_token):
		try:
			page = self._parse_re(Parser._PageRe)
			if page:
				panel = "1"
			else:
				# if line above text is empty, we've started a new panel
				panel = str(int(last_token.panel) + 1) if self._empty_line_above else last_token.panel
				page = last_token.page
			line = self._cur_line
			text = self._parse_text()
			return [self.Token(page, panel, text, line)]
		except self.ParserEndError:
			return [None]

	def _parse_text(self):
		text = self._get_line()
		self._next_line()
		# remove [ and ]
		return re.sub(r"[\[\]]", "", text)

if __name__ == '__main__':
	import doctest

	doctest.testmod()
